package com.mic.yzzn.plc.common.instructions.request;

import org.apache.commons.lang.StringUtils;

import com.mic.yzzn.plc.common.ins.datastructure.PLCDataRegisterNumber;
import com.mic.yzzn.plc.common.instructions.basic.PLCRequestInstruction;

/**
 * Created by ASH on 16/3/8.
 */
public class PLCDataRegisterReadInstruction extends PLCDataRegisterInstruction
{
	/**
	 * 初始化方法
	 */
    public PLCDataRegisterReadInstruction()
    {
        new PLCDataRegisterInstruction();

        requestCode = PLCRequestInstruction.READ_DATA_AREA_INS;
    }

    /**
     * 用字符串初始化
     */
    @Override
    public String initWithString(String instructionString) throws IllegalArgumentException
    {
    	String tempResult = super.initWithString(instructionString);
//    	System.out.println(tempResult);

    	// 判断请求码与当前指令的请求码是否符合
    	int requestCodeLength = requestCode.length();
    	if (!(StringUtils.substring(tempResult, 0, requestCodeLength).equals(requestCode)))
		{
			throw new IllegalArgumentException("PLCSingleContactorReadInstruction's requestCode must be \"" + requestCode +"\"");
		}
    	
    	// 截取请求码
    	tempResult = StringUtils.substringAfter(tempResult, requestCode);
//    	System.out.println(tempResult);

    	// 获取数据代码
    	String dataCode = tempResult.substring(0, 1);
    	this.dataCode = dataCode;
    	
    	// 截断数据代码
    	tempResult = StringUtils.substringAfter(tempResult, dataCode);
//    	System.out.println(tempResult);

    	// 判断数据范围是否正确
    	if (tempResult.length() < 10)
		{
			throw new IllegalArgumentException("the length PLCDataRegisterNumber's beginNumber and endNumber must be 5");
		}
    	
    	// 设置数据范围
    	this.dataRegisterNumber = new PLCDataRegisterNumber(tempResult.substring(0, 5), tempResult.substring(5, 10));
    	
    	// 截断数据范围
    	tempResult = StringUtils.substringAfter(tempResult, dataRegisterNumber.toString());
    	
    	return tempResult;
    }
    
}
